<?php

namespace app\common\traits;

use think\exception\HttpResponseException;
use think\Response;

/**
 * Trait JumpTrait
 * @package app\common\traits
 */
trait UapiJumpTrait
{

    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 返回的数据
     * @param int $code 返回的 code
     * @return void
     * @throws HttpResponseException
     */
    protected function success($msg = '', $data = '', $code = 0)
    {
        $result = [
            'errno' => $code,
            'message' => $msg,
            'data' => $data
        ];
        $response = json($result);
        throw new HttpResponseException($response);
    }

    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param mixed $data 返回的数据
     * @param int $code 返回的 code
     * @return void
     * @throws HttpResponseException
     */
    protected function error($msg = '', $data = '', $code = 199)
    {
        $result = [
            'errno' => $code,
            'message' => $msg,
            'data' => $data
        ];
        $response = json($result);
        throw new HttpResponseException($response);
    }

    /**
     * 返回封装后的 API 数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param int $code 返回的 code
     * @param mixed $msg 提示信息
     * @param array $header 发送的 Header 信息
     * @return void
     * @throws HttpResponseException
     */
    protected function result($data, $code = 0, $msg = '', array $header = [])
    {
        $result = [
            'errno' => $code,
            'message' => $msg,
            'time' => time(),
            'data' => $data
        ];
        $type = 'json';
        $response = Response::create($result, $type)->header($header);

        throw new HttpResponseException($response);
    }
}
